<template>
  <div class="goods-manager">
    <GoodsAdd text="click me to add goods"/>
    <template v-for="(goods, index) in goodsCollection" :key="index">
      <GoodsManage :goods="goods" />
    </template>
  </div>
</template>

<script lang="ts" setup>
 import GoodsManage from '@/components/GoodsManage.vue'
 import GoodsEdit from '@/components/GoodsEdit.vue'
 import GoodsAdd from '@/components/GoodsAdd.vue'
 import { ref, onBeforeMount, onMounted, provide, watch } from "vue"
 import {UserService, GoodsService, GoodsTypeService} from '@/service'
 import { useRouter } from "vue-router"
 const router = useRouter()
 const goodsCollection = ref<Array<Goods>>([])

 const currentShowIndex = ref(-1)
 const shouldUpdate = ref(false)
 const goodsTypes = ref<Array<GoodsType>>([])
 provide('currentShowIndex', currentShowIndex);
 provide('shouldUpdate', shouldUpdate)
 provide('goodsTypes', goodsTypes)

 async function loadCollections() {
   let data = await GoodsService.findAll();
   goodsCollection.value = data
 }
 
 watch(shouldUpdate, async (value, oldvalue) => {
   await loadCollections()
   shouldUpdate.value = false
 })
 
 onMounted(async () => {
   // TODO 如果没有登录就跳转到这里，重定向到主界面
   let {data} = await UserService.getLoginUser()
   if(data == null || data != 'admin') {
     router.push({name: 'Home'})
     return
   }

   await loadCollections()

   goodsTypes.value = await GoodsTypeService.findAll()
 })
</script>


<style lang="scss" scoped>
 div.goods-manager {
   display: flex;
   flex-direction: column;
 }
</style>